<template>
  <div>
    <el-upload
      :action="uploadURL"
      :on-preview="handlePreview"
      :on-remove="handleRemove"
      list-type="picture"
      :headers="headerObj"
      :on-success="handlerSuccess"
    >
      <el-button size="small" type="primary">点击上传</el-button>
    </el-upload>
    <el-dialog title="图片预览" :visible.sync="imgVisible" width="50%">
      <img :src="previewImgURL" alt="" class="preview-img" />
    </el-dialog>
  </div>
</template>

<script>
import { getItem } from '@/utils/storage' // 按需导入
export default {
  name: 'GoodsImg',
  data() {
    return {
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      headerObj: {
        Authorization: getItem('token')
      },
      previewImgURL: '',
      imgVisible: false
    }
  },
  inject: ['addGoodsForm'],
  methods: {
    // 处理预览图片的功能
    handlePreview(file) {
      this.previewImgURL = file.response.data.url
      this.imgVisible = true
    },
    // 处理移出图片的功能
    handleRemove(file) {
      const index = this.addGoodsForm.pics.findIndex(
        item => item.pic === file.response.data.tmp_path
      )
      this.addGoodsForm.pics.splice(index, 1)
    },
    // 上传成功的函数handlerSuccess
    handlerSuccess(response) {
      this.addGoodsForm.pics.push({
        pic: response.data.tmp_path
      })
    }
  }
}
</script>

<style scoped lang="less">
.preview-img {
  width: 100%;
}
</style>
